package com.coder520.servicestudy;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();
//    private StudentService mStudentService;
    private IStudentManager mStudentService;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        Intent intent = new Intent(MainActivity.this, StudentService2.class);
        //通过Context对象的startService方法
//        startService(intent);
        //和我们register一样,  bindService, 一定要记得 unBindService
        bindService(intent, mServiceConnection, BIND_AUTO_CREATE);
    }

    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
//            mStudentService = ((StudentService.MyBinder)service).getService();

//            Log.d(TAG, "code520 student is:" + mStudentService.getStudent());
            mStudentService = IStudentManager.Stub.asInterface(service);
            try {
                mStudentService.addStudent(new Student("老李", 20));
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                mStudentService.printString("laoli..20");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            try {
                Log.d(TAG, "Student count is:" + mStudentService.getStudentCount());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mStudentService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
//        Intent intent = new Intent(MainActivity.this, StudentService.class);
//        stopService(intent);
    }
}
